<template>
  <div :class="prefixCls">
    <Popover
      title=""
      trigger="click"
      :overlayClassName="`${prefixCls}__overlay`"
      @visible-change="handleChange"
      transitionName="{}"
    >
      <Badge
        :count="totalUnreadCount"
        :numberStyle="{
          // width: '14px',
          // height: '14px',
          // minWidth: '14px',
          // fontSize: '8.4px',
          // lineHeight: '14px',
          // marginTop: '14px',
          // marginRight: '7px',
        }"
        :offset="[0, 10]"
      >
        <BellOutlined />
      </Badge>
      <template #content>
        <NoticeList :list="notificationsList" @read="handleItemAsRead" />
      </template>
    </Popover>
  </div>
</template>
<script lang="ts" setup>
  import { onMounted, ref } from 'vue';
  import { Popover, Badge } from 'ant-design-vue';
  import { BellOutlined } from '@ant-design/icons-vue';
  import { ListItem } from './data';
  import NoticeList from './NoticeList.vue';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { useWebsocketStoreWithOut } from '/@/store/modules/thingsboard/websocket';

  const { prefixCls } = useDesign('header-notify');
  const notificationsList = ref<ListItem[]>([]);
  const ws = useWebsocketStoreWithOut();

  const totalUnreadCount = ref<number>(0);

  /**
   * 将单个消息标识为已读，同时返回新的未读消息列表
   * @param id 点击已读的通知消息id
   */
  const handleItemAsRead = (id: string) => {
    // 发送已读消息请求，返回新消息列表
    ws.send(
      ws.getAndIncrementCmdId(),
      { markAsReadCmd: { cmdId: ws.getCmdId, notifications: [id] } },
      (res) => pushNotificationsList(res),
      'notifications',
    );
  };

  /**
   * 首次订阅未读消息总数量
   */
  const subUnreadCount = () => {
    ws.send(
      ws.getAndIncrementCmdId(),
      { unreadCountSubCmd: { cmdId: ws.getCmdId } },
      (res) => {
        totalUnreadCount.value = res.totalUnreadCount;
      },
      'notifications',
    );
  };

  /**
   * 取消订阅消息
   */
  const cancelSubCmd = () => {
    ws.send(ws.getCmdId, { unsubCmd: { cmdId: ws.getCmdId } }, () => {}, 'notifications');
  };

  /**
   * 通知消息列表显隐
   * @param visible 显隐标识 布尔值
   */
  const handleChange = (visible: boolean) => {
    cancelSubCmd();
    if (visible) {
      // 显示列表
      getNotificationsList();
    } else {
      // 隐藏列表
      subUnreadCount();
    }
  };

  /**
   * 初始化未读消息列表
   */
  const getNotificationsList = () => {
    ws.send(
      ws.getAndIncrementCmdId(),
      { unreadSubCmd: { cmdId: ws.getCmdId, limit: 6 } },
      (res) => pushNotificationsList(res),
      'notifications',
    );
  };

  /**
   * 将ws返回的未读消息数组添加到列表中
   * @param res ws返回的未读消息数组
   */
  const pushNotificationsList = (res: Recordable) => {
    // 未读消息总数量
    totalUnreadCount.value = res.totalUnreadCount;
    // 置空消息列表
    notificationsList.value = [];
    // 消息列表添加新消息
    res.notifications.forEach((item: Recordable) => {
      notificationsList.value.push({
        id: item.id,
        subject: item.subject,
        text: item.text,
        actionButtonConfig: item.additionalConfig.actionButtonConfig,
        icon: item.additionalConfig.icon,
        createdTime: item.createdTime,
        info: item.info,
      });
    });
  };

  onMounted(() => subUnreadCount());
</script>
<style lang="less">
  @prefix-cls: ~'@{namespace}-header-notify';

  .@{prefix-cls} {
    padding-top: 2px;

    &__overlay {
      // max-width: 360px;
      // max-width: 100vw;
      // max-height: 80vh;
    }

    .ant-tabs-content {
      width: 300px;
    }

    .ant-badge {
      font-size: 18px;

      .ant-badge-multiple-words {
        padding: 0.5px 2px;
      }

      svg {
        width: 0.9em;
      }
    }
  }
</style>
